import { Injectable, HttpException, HttpStatus } from '@nestjs/common';
import { Repository } from 'typeorm'
import { InjectRepository } from '@nestjs/typeorm'
import { ArticleLike } from '../../entities/articleLike.entity'
import { Article } from 'src/entities/article.entity';
import { User } from 'src/entities/user.entity';
@Injectable()
export class ArticleLikeService {

    constructor(
        @InjectRepository(Article)
        private readonly articleRepository: Repository<Article>,
        @InjectRepository(ArticleLike)
        private readonly articleLikeRepository: Repository<ArticleLike>,
        @InjectRepository(User)
        private readonly UserRepository: Repository<User>
    ) {

    }

    async create(userId: string, article_id: string) {
        // 查询是否存在文章
        const article = await this.articleRepository.findOne({ where: { article_id } })

        if (!article) {
            throw new HttpException('文章不存在', HttpStatus.BAD_REQUEST)
        }
        // 查询是否已添加
        let articleLike = await this.articleLikeRepository.findOne({ where: { user: { id: userId }, article: { article_id } } })

        if (articleLike) return

        articleLike = await this.articleLikeRepository.save({
            user: await this.UserRepository.findOne({ where: { id: userId } }),
            article
        })
        return articleLike

    }
    async delete(userId: string, article_id: string) {

        await this.articleLikeRepository.delete({
            article: { article_id },
            user: { id: userId }
        })

    }

}
